Day4做的header在串會員功能後想做一點小變動,下拉選單的判斷是要整區移除並且加上登入的判斷。
回顧一下DAY4的code,會員專區/登出的狀態為是會員的時候出現,會員登入/註冊則是非會員狀態時出現,分別將他們做成小元件,再用isLoggedIn
變數去判斷要顯示哪一個
function Header(){
const [menuToggle, setMenuToggle] = useState(false)
const [memberMenuIsShown, setMemberMenuIsShown] = useState(false);
function IsMember(props) {
return (
<ul className={`member_list ${memberMenuIsShown ? "open" : ""}`}>
<li>
<a href="member.php">會員專區</a>
</li>
<li>
<a href="javascript:;">登出</a>
</li>
</ul>
)
}
function NotMember(props) {
return (
<ul className={`nonmemember_list ${memberMenuIsShown ? "open" : ""}`}>
<li>
<a href="login.php">會員登入</a>
</li>
<li>
<a href="signup.php">註冊</a>
</li>
</ul>
)
}
function MemberList(props) {
const isLoggedIn = true;
if (isLoggedIn) {
return <IsMember />;
}
return <NotMember />;
};
return(
<header className={menuToggle ? 'navbar open' : 'navbar'} >
//--略
<div className="container__icon is_member">
<div className="member "
onMouseEnter={() => setMemberMenuIsShown(true)}
onMouseLeave={() => setMemberMenuIsShown(false)}
onClick={() => setMemberMenuIsShown((current) => !current)}>
<a className="icon" href="javascript:;"
>
<img src={icon_member} alt="icon_member"/>
</a>
<MemberList/>
</div>
</div>
//--略
</header>
)
}
export default Head
有了firebase可以驗證是否為會員並把這個功能先寫入,建立user變數,用三元式子判斷要出現哪一個,不像我上一個寫的這麼複雜。
function Header(){
const [menuToggle, setMenuToggle] = useState(false)
const [memberMenuIsShown, setMemberMenuIsShown] = useState(false);
const [user,setUser] = useState(null)
;
useEffect(() => {
firebase.auth().onAuthStateChanged((currentUser) => {
if (currentUser) {
var uid = currentUser.uid;
setUser(currentUser)
console.log('會員')
} else {
console.log('非會員')
}
});
},[])
return(
<header className={menuToggle ? 'navbar open' : 'navbar'} >
//--略
<div className="container__icon is_member">
<div className="member "
onMouseEnter={() => setMemberMenuIsShown(true)}
onMouseLeave={() => setMemberMenuIsShown(false)}
onClick={() => setMemberMenuIsShown((current) => !current)}>
<a className="icon" href="#"
>
<img src={icon_member} alt="icon_member"/>
</a>
{user ? (
<ul className={`member_list ${memberMenuIsShown ? "open" : ""}`}>
<li>
<a href="member.php">會員專區</a>
</li>
<li>
<a href="#">登出</a>
</li>
</ul>
):(
<ul className={`nonmemember_list ${memberMenuIsShown ? "open" : ""}`}>
<li>
<Link to="/login">會員登入</Link>
</li>
<li>
<Link to="/signup">註冊</Link>
</li>
</ul>
)}
</div>
//--略
</header>
)
}
export default Header